<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Http\Request;

class Leyu extends AbstractApi
{
    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public function sign(array $array, string $secret_key): string
    {
        ksort($array);
        $sign = '';
        foreach($array as $k => $v){
            $sign .= $k . $v;
        }
        return strtoupper(md5($sign . $secret_key));
    }

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $please = [
            'product_code'  => $bean->getGoodsId(), //商品编码
            'notify_url'    => $bean->getNotifyUrl(), //异步回调地址
            'buy_num'       => $bean->getRechargeNum() * $bean->getStartCharging(),//充值数量,
            'account'       => $bean->getAccount(),
            'out_trade_no'  => $bean->getOrderNo(), //订单号
            'extend'        => ''
        ];
        $array = [
            'app_id'        => $bean->getSupplierNum(), //商户密钥
            'method'        => 'hr.order.direct.add',
            'timestamp'     => date('Y-m-d H:i:s',time()),
            'version'       => '1.0',
            'biz_content'   => json_encode($please)
        ];
        $array['sign'] = $this->sign($array, $bean->getSecretKey());
        return $array;
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('status', '');
        $order_sn = $request->input('out_trade_no', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, [2, 3]))->setRechargeSuccess($status == 2);
    }

    /**
     * @return mixed
     */
    public function apiNotifySuccess(): mixed
    {
        return response('success');
    }
}
